import request from './request';
import { uuid } from "@/utils/tool";

const fillNoise = (data) => {
  return Object.assign({_t: new Date().getTime(), _nonce: uuid()}, data || {});
};

export const post = (url, data, timeout) => {
  if (!(data && Array.isArray(data))) {
    data = fillNoise(data);
    Object.defineProperty(data, 'button', {enumerable: false});
    Object.defineProperty(data, 'createTime', {enumerable: false});
  }

  return request({
    url: url,
    method: 'post',
    timeout: timeout,
    headers: {
      'Content-Type': 'application/json',
      'Client-Flag': 'pc'
    },
    data: JSON.stringify(data)
  });
};

const runScript = (id, data) => {
  return post('/codeless/script/run/' + id, {data: data || {}});
};

export const get = (url) => {
  return request({
    url: url,
    method: 'get'
  });
};

export const login = data => {
  return post('/login', data);
};

export const logout = () => {
  return post('/logout');
};

export const captcha = () => {
  return request({
    url: '/captcha',
    method: 'post',
    responseType: 'arraybuffer',
    data: JSON.stringify(fillNoise({}))
  });
};

export const upload = (data) => {
  const formData = new FormData();
  for (const p in data) {
    formData.append(p, data[p]);
  }

  return request({
    url: '/file/upload',
    method: 'post',
    timeout: 100 * 60 * 60 * 1000,
    headers: {'Content-Type': 'multipart/form-data'},
    data: formData
  });
};

export const download = (fileId) => {
  return request({
    url: '/file/download',
    method: 'post',
    timeout: 100 * 60 * 60 * 1000,
    responseType: 'arraybuffer',
    data: JSON.stringify(fillNoise({id: fileId}))
  });
};

export const downloadAll = (affixId) => {
  return request({
    url: '/file/downloadAll',
    method: 'post',
    timeout: 100 * 60 * 60 * 1000,
    responseType: 'arraybuffer',
    data: JSON.stringify(fillNoise({affixId: affixId}))
  });
};

export const createQrCode = (message) => {
  return request({
    url: '/qrcode',
    method: 'post',
    responseType: 'arraybuffer',
    data: JSON.stringify(fillNoise({message: message}))
  });
};

export const queryFile = (id) => {
  return post('/file/queryItem', {id: id});
};

export const queryAffix = (affixId) => {
  return post('/file/queryItems', {affixId: affixId});
};

export const deleteAffix = (fileId) => {
  return post('/file/deleteItem', {id: fileId});
};

export const uploadFile = (url, data) => {
  const param = new FormData();
  for (const p in data) {
    param.append(p, data[p]);
  }

  return request({
    url: url,
    method: 'post',
    timeout: 100 * 60 * 60 * 1000,
    headers: {'Content-Type': 'multipart/form-data'},
    data: param
  });
};

export const downloadFile = (url, data) => {
  return request({
    url: url,
    method: 'post',
    timeout: 100 * 60 * 60 * 1000,
    responseType: 'arraybuffer',
    data: JSON.stringify(fillNoise(data))
  });
};

export const downloadFileLocal = (id) => {
  return download(id).then(res => saveFileLocal(res));
};

export const downloadAffixLocal = (id) => {
  return new Promise((resolve, reject) => {
    downloadAll(id).then(res => {
      saveFileLocal(res);
      resolve();
    }).catch(e => reject(e));
  });
};

export const saveFileLocal = (res) => {
  let fileName = res.headers['content-disposition']
      ? res.headers['content-disposition'].split('=')[1]
      : '未命名';
  fileName = fileName.replace(/"/g, '');

  let blob;
  if('msSaveOrOpenBlob' in navigator) {
    if (fileName.endsWith('.xls') || fileName.endsWith('.xlsx')) {
      blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});
    } else {
      blob = new Blob([res.data], {type: 'application/octet-stream'});
    }
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    blob = new Blob([res.data], {type: 'application/octet-stream'});
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    downloadElement.download = decodeURI(fileName);
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
  }
};

export default {
  post,
  get,
  login,
  logout,
  captcha,
  upload,
  download,
  downloadAll,
  createQrCode,
  queryFile,
  queryAffix,
  deleteAffix,
  uploadFile,
  downloadFile,
  downloadFileLocal,
  downloadAffixLocal,
  saveFileLocal,
  runScript
}
